package org.aynu.paymentservice.service.impl;

import org.aynu.paymentservice.common.PaymentsResponse;
import org.aynu.paymentservice.domain.Payments;
import org.aynu.paymentservice.feign.OrderServiceClient;
import org.aynu.paymentservice.feign.PropertyServiceClient;
import org.aynu.paymentservice.mapper.PaymentsMapper;
import org.aynu.paymentservice.service.IPaymentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 支付表 服务实现类
 * </p>
 *
 * @author 小粥
 * @since 2025-03-04
 */
@Service
public class PaymentsServiceImpl extends ServiceImpl<PaymentsMapper, Payments> implements IPaymentsService {

    private final OrderServiceClient orderServiceClient;
    private final PropertyServiceClient propertyServiceClient;

    @Autowired
    public PaymentsServiceImpl(OrderServiceClient orderServiceClient, PropertyServiceClient propertyServiceClient) {
        this.orderServiceClient = orderServiceClient;
        this.propertyServiceClient = propertyServiceClient;
    }

    @Override
    public PaymentsResponse<Integer> createPayment(Payments request) {
        // 插入支付记录
        Integer result = baseMapper.insert(request);

        // 根据支付类型更新状态
        if (request.getOrderId() != null) {
            // 订单支付
            Map<String, Object> map = Map.of(
                    "orderId", request.getOrderId(),
                    "status", "已支付"
            );
            orderServiceClient.updateOrderStatus(map);
        } else if (request.getFeeId() != null) {
            // 物业费支付
            Map<String, Object> map = Map.of(
                    "feeId", request.getFeeId(),
                    "status", "已支付",
                    "paidAt", request.getCreatedAt().toString()
            );
            propertyServiceClient.updatePropertyFeeStatus(map);
        } else {
            throw new IllegalArgumentException("必须提供 orderId 或 feeId");
        }

        return PaymentsResponse.success(result);
    }
}